import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import { Card, Table, Button, Space, Modal, Form, Input, Select, message, Popconfirm, Upload, Tabs } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, UploadOutlined } from '@ant-design/icons';
import { request } from 'umi';
import ReactQuill from 'react-quill';
import 'react-quill/dist/quill.snow.css';
import moment from 'moment';

const { TabPane } = Tabs;
const { TextArea } = Input;

// 获取内容列表
const fetchContents = async (params) => {
  return request('/api/v1/miniprogram/content', {
    method: 'GET',
    params,
  });
};

// 创建内容
const createContent = async (data) => {
  return request('/api/v1/miniprogram/content', {
    method: 'POST',
    data,
  });
};

// 更新内容
const updateContent = async (data) => {
  return request(`/api/v1/miniprogram/content/${data.id}`, {
    method: 'PUT',
    data,
  });
};

// 删除内容
const deleteContent = async (id) => {
  return request(`/api/v1/miniprogram/content/${id}`, {
    method: 'DELETE',
  });
};

const ContentManagement = () => {
  const [contents, setContents] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [modalTitle, setModalTitle] = useState('添加内容');
  const [form] = Form.useForm();
  const [editingId, setEditingId] = useState(null);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
  });
  const [activeTab, setActiveTab] = useState('article');

  // 获取内容列表
  const fetchContentList = async () => {
    try {
      setLoading(true);
      const res = await fetchContents({
        page: pagination.current,
        pageSize: pagination.pageSize,
        type: activeTab,
      });
      if (res.success) {
        setContents(res.data.list || []);
      } else {
        message.error(res.message || '获取内容列表失败');
      }
    } catch (error) {
      console.error('获取内容列表出错:', error);
      message.error('获取内容列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchContentList();
  }, [pagination.current, pagination.pageSize, activeTab]);

  // 表格列定义
  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      width: 80,
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '封面图',
      dataIndex: 'cover_image',
      key: 'cover_image',
      render: (text) => text ? <img src={text} alt="封面" style={{ width: 80, height: 50, objectFit: 'cover' }} /> : '-',
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      render: (text) => {
        const typeMap = {
          'article': '文章',
          'notice': '公告',
          'help': '帮助',
          'about': '关于我们',
        };
        return typeMap[text] || text;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status) => (
        <span style={{ color: status === 1 ? '#52c41a' : '#ff4d4f' }}>
          {status === 1 ? '已发布' : '未发布'}
        </span>
      ),
    },
    {
      title: '排序',
      dataIndex: 'sort',
      key: 'sort',
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at',
      render: (text) => moment(text*1000).format('YYYY-MM-DD HH:mm:ss'),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space size="middle">
          <Button 
            type="primary" 
            icon={<EditOutlined />} 
            size="small"
            onClick={() => handleEdit(record)}
          >
            编辑
          </Button>
          <Popconfirm
            title="确定要删除此内容吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="primary" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 处理添加内容
  const handleAdd = () => {
    setModalTitle('添加内容');
    setEditingId(null);
    form.resetFields();
    form.setFieldsValue({ 
      type: activeTab,
      status: 1,
      sort: 0,
    });
    setModalVisible(true);
  };

  // 处理编辑内容
  const handleEdit = (record) => {
    setModalTitle('编辑内容');
    setEditingId(record.id);
    form.setFieldsValue({
      title: record.title,
      cover_image: record.cover_image,
      content: record.content,
      type: record.type,
      status: record.status,
      sort: record.sort,
      summary: record.summary,
    });
    setModalVisible(true);
  };

  // 处理删除内容
  const handleDelete = async (id) => {
    try {
      const res = await deleteContent(id);
      if (res.success) {
        message.success('删除成功');
        fetchContentList();
      } else {
        message.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除内容出错:', error);
      message.error('删除失败');
    }
  };

  // 处理表单提交
  const handleSubmit = async (values) => {
    try {
      setLoading(true);
      let res;
      if (editingId) {
        // 更新内容
        res = await updateContent({
          ...values,
          id: editingId,
        });
      } else {
        // 创建内容
        res = await createContent(values);
      }

      if (res.success) {
        message.success(editingId ? '更新成功' : '创建成功');
        setModalVisible(false);
        fetchContentList();
      } else {
        message.error(res.message || (editingId ? '更新失败' : '创建失败'));
      }
    } catch (error) {
      console.error('保存内容出错:', error);
      message.error(editingId ? '更新失败' : '创建失败');
    } finally {
      setLoading(false);
    }
  };
  const token = localStorage.getItem('token');
  // 上传配置
  const uploadProps = {
    name: 'file',
    action: '/api/v1/upload',
    headers: {'Authorization':`Bearer ${token}`} ,
    onChange(info) {
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
        // 设置表单字段值
        form.setFieldsValue({
          cover_image: info.file.response.data,
        });
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
  };

  // 处理标签页切换
  const handleTabChange = (key) => {
    setActiveTab(key);
    setPagination({
      ...pagination,
      current: 1,
    });
  };

  // 处理分页变化
  const handleTableChange = (pagination) => {
    setPagination(pagination);
  };

  return (
    <PageContainer>
      <Card>
        <Tabs activeKey={activeTab} onChange={handleTabChange}>
          <TabPane tab="文章" key="article" />
          <TabPane tab="公告" key="notice" />
          <TabPane tab="帮助" key="help" />
          <TabPane tab="关于我们" key="about" />
        </Tabs>

        <div style={{ marginBottom: 16 }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={handleAdd}
          >
            添加{activeTab === 'article' ? '文章' : activeTab === 'notice' ? '公告' : activeTab === 'help' ? '帮助' : '关于我们'}
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={contents}
          rowKey="id"
          loading={loading}
          pagination={pagination}
          onChange={handleTableChange}
        />

        <Modal
          title={modalTitle}
          visible={modalVisible}
          onCancel={() => setModalVisible(false)}
          footer={null}
          width={800}
        >
          <Form
            form={form}
            layout="vertical"
            onFinish={handleSubmit}
          >
            <Form.Item
              name="title"
              label="标题"
              rules={[{ required: true, message: '请输入标题' }]}
            >
              <Input placeholder="请输入标题" />
            </Form.Item>

            <Form.Item
              name="type"
              label="类型"
              rules={[{ required: true, message: '请选择类型' }]}
            >
              <Select>
                <Select.Option value="article">文章</Select.Option>
                <Select.Option value="notice">公告</Select.Option>
                <Select.Option value="help">帮助</Select.Option>
                <Select.Option value="about">关于我们</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="cover_image"
              label="封面图"
            >
              <Input placeholder="请上传封面图" addonAfter={
                <Upload {...uploadProps}>
                  <Button icon={<UploadOutlined />}>上传</Button>
                </Upload>
              } />
            </Form.Item>

            <Form.Item
              name="summary"
              label="摘要"
            >
              <TextArea rows={3} placeholder="请输入摘要" />
            </Form.Item>

            <Form.Item
              name="content"
              label="内容"
              rules={[{ required: true, message: '请输入内容' }]}
            >
              <ReactQuill
                theme="snow"
                style={{ height: 300 }}
                placeholder="请输入内容"
              />
            </Form.Item>

            <Form.Item
              name="status"
              label="状态"
              rules={[{ required: true, message: '请选择状态' }]}
            >
              <Select>
                <Select.Option value={1}>发布</Select.Option>
                <Select.Option value={0}>草稿</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item
              name="sortOrder"
              label="排序"
            >
              <Input type="number" placeholder="请输入排序值，值越小越靠前" />
            </Form.Item>

            <Form.Item
              name="isTop"
              label="是否置顶"
            >
              <Select>
                <Select.Option value={1}>是</Select.Option>
                <Select.Option value={0}>否</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item>
              <Space>
                <Button type="primary" htmlType="submit" loading={loading}>
                  保存
                </Button>
                <Button onClick={() => setModalVisible(false)}>
                  取消
                </Button>
              </Space>
            </Form.Item>
          </Form>
        </Modal>
    
      </Card>
    </PageContainer>
  );
};

export default ContentManagement;